package com.dhecp.project.purchase.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.core.utils.ReadExcel;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.business.domain.ProductActiveComponent;
import com.dhecp.project.business.service.ProductActiveService;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.purchase.domain.Distribution;
import com.dhecp.project.purchase.service.DistributionService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp Distribution
 * @description: 1688铺货单 控制层
 * @author: hlf
 * @create: 2022-08-27 09:52
 */
@Controller
@RequestMapping("/purchase/distribution")
public class DistributionController extends BaseModuleController {


    private String prefix = "purchase/distribution";
    private String moduleTable = ModuleTable.DISTRIBUTION;

    @Autowired
    private DistributionService businessService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    
    @Autowired
    private ProductActiveService productActiveService;

    /**
     *@Description: 打开查询列表页
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("purchase:distribution:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new Distribution()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/distribution"); //页面路径
        params.put("toolBarWidth", 150);
//        params.put("checkBox", "yes");
        params.put("ali1688AppKey", ApiConfig.getAli1688AppKey());
        params.put("ali1688EcpApiUrl", ApiConfig.getAli1688EcpApiUrl());
        ModelAndView mv = this.openListPage(params);
        mv.addObject("purchase", "distribution");
        return mv;
    }

    /**
     *@Description: 跳转铺货页面
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("purchase:distribution:view")
    @GetMapping("/account")
    public ModelAndView account(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv.addObject("purchase", "distribution");
        mv.addObject("moduleTable", moduleTable);
        mv.addObject("ali1688AppKey", ApiConfig.getAli1688AppKey());
        mv.addObject("ali1688EcpApiUrl", ApiConfig.getAli1688EcpApiUrl());
        mv.setViewName(prefix + "/alaccount");
        return mv;
    }

    
    /**
     *@Description: 打开制单页
     *@Param: [params] nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("purchase:distribution:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new Distribution()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        Distribution distribution = new Distribution();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            distribution = businessService.findByGuid(params);


            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
            params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                for (SysDictionaryForPageField dicFields : dicFieldsList){
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);

                    if (distribution!=null){
                        Map<String, Object> infoData = TypeUtils.entityToMap(distribution);
                        fieldsListMap.put("fieldContent", infoData.get(fieldsListMap.get("fields")));
                    }else{
                        fieldsListMap.put("fieldContent", "");

                    }
                    if (fieldsListMap.get("fieldFrontType") == null){
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }

                    if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    }else {	//隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);				//显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
        mv.addObject("distribution", distribution);	//字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/distribution_edit");
        return mv;

    }

    /**
     *@Description: 打开流转页
     *@Param: [params] fType 必要参数：审核类型（flow_go：流转，flow_back：退回）
     *@Param: [params] infoMap 必要参数：非网格字段（包括所有显示和隐藏的字段），json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("purchase:distribution:flow")
    @PostMapping("/flowpage")
    @ResponseBody
    public AjaxResult flowPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("prefix", prefix);
        return openFlowPage(params);
    }


    /**
     *@Description: 查询页 列表数据
     *@Param: [params]
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("purchase:distribution:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<Distribution> distributionList = new ArrayList<Distribution>();
        try {
            distributionList = businessService.queryList2(params);
            for (Distribution item:distributionList
                 ) {
//                sonData = purchaseService.querySonList2(item.getGuid());
//                StringBuilder sCode = new StringBuilder();
//                StringBuilder sName= new StringBuilder();
//                for (DistributionSon item2:sonData
//                ) {
//                    sCode.append(!item2.getsCode().equals("") ? item2.getsCode() + "," + item.getsCode() : item2.getsCode() + (item.getsCode() != null ? item.getsCode() : ""));
//                    sCode.append(item2.getsCode()).append(",");
//                    sName.append(item2.getsName()).append(",");
//                }
                item.setsCode(item.getsCode() != null?item.getsCode().substring(0,item.getsCode().length()-1):"");
                item.setsName(item.getsName() != null?item.getsName().substring(0,item.getsName().length()-1):"");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e));
        }
        return getDataTable(distributionList);
    }




    /**
     *@Description: 数据导出Excel
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("purchase:distribution:export")
    @Log(title = "铺货单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new Distribution());

        List<Distribution> list = businessService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<Distribution> util = new ExportExcelUtils<Distribution>(moduleTable,new Distribution());
        return util.exportExcel(list, fieldList, "铺货单", "export");
    }

    /**
     *@Description: 导出Excel导入模板
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("purchase:distribution:import")
    @Log(title = "铺货单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new Distribution());

        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<Distribution> util = new ExportExcelUtils<Distribution>(moduleTable,new Distribution());
        return util.exportExcel(null, fieldList, "铺货单导入模板", "template");
    }

    /**
     *@Description: 保存数据
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions(value={"purchase:distribution:add","purchase:distribution:edit","purchase:distribution:delete"},logical= Logical.OR)
    @Log(title = "铺货单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= businessService.saveData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 保存数据
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions(value={"purchase:distribution:add","purchase:distribution:edit","purchase:distribution:delete"},logical= Logical.OR)
    @Log(title = "铺货单", businessType = BusinessType.UPDATE)
    @PostMapping("/saveData")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSaveSon(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= businessService.saveDataSon(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 保存铺货关联数据（批量）
     */
    @GetMapping("/saveDataLocal")
    @ResponseBody
    public AjaxResult saveDataLocal(){

        try {
            List<List<String>> rows = ReadExcel.getRowsByFile("d:\\Users\\Administrator\\Desktop\\导入ERP\\子件铺货关联1688SKUID信息表.xlsx", 0);
        	for (int i = 0; i < rows.size(); i++) {
        		System.out.println("---第" + i + "行---");
        		List<String> row = rows.get(i);
        		
        		String code = row.get(0);
        		List<ProductActiveComponent> listProductActiveComponent = productActiveService.queryProductActiveComponentByCode(code);
        		if (listProductActiveComponent == null || listProductActiveComponent.size() != 1) {
					continue;
				}
        		ProductActiveComponent productActiveComponent = listProductActiveComponent.get(0);
        		
        		String skuid = row.get(1);
        		Distribution distribution = businessService.findByPcodeAndSkuid(productActiveComponent.getPcode(), skuid);
        		if (distribution == null) {
					continue;
				}
        		Map<String, Object> params = new HashMap<String, Object>();
        		
        		JSONObject JO = new JSONObject();
                JO.put("moduleTable", moduleTable);
                JO.put("guid", distribution.getGuid());
                JO.put("goodsID", distribution.getGoodsID());
                JO.put("supplierID", distribution.getSupplierID());
                JO.put("sKUID", distribution.getsKUID());
                JO.put("sPECID", distribution.getsPECID());
                JO.put("sCode", productActiveComponent.getCode());
                params.put("infoItem", JO.toJSONString());
                businessService.saveDataSon(params);
        	}
		} catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
		}

        return AjaxResult.success();
    }

    /**
     * 删除推广项目
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @RequiresPermissions("purchase:distribution:delete")
    @Log(title = "删除铺货单", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult customerDelete(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= businessService.deleteData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


}